package com.base.worker;

import com.base.client.HttpSender;
import com.base.domain.request.HeartbeatRequest;
import com.base.domain.request.RegisterRequest;
import com.base.domain.response.HeartbeatResponse;
import com.base.domain.response.RegisterResponse;

/**
 * 负责向register-server发起注册申请的线程
 * @ClassName: RegisterClientWorker
 * @Description: 
 * @Author xuyou
 * @DateTime 2021年3月5日 下午2:59:19
 */
public class RegisterClientWorker extends Thread {

	public static final String SERVICE_NAME = "order-service";
	public static final String HOSTNAME = "order01";
	public static final String IP = "localhost";
	public static final int PORT = 9000;

	
	/**
	 * 服务实例id
	 */
	private String serviceInstanceId;
	/**
	 * 是否完成服务注册
	 */
	private Boolean isRegister;
	/**
	 * http通信组件
	 */
	private HttpSender httpSender;
	
	public RegisterClientWorker(String serviceInstanceId) {
		this.serviceInstanceId = serviceInstanceId;
		this.httpSender = new HttpSender();
		this.isRegister = false;
	}

	@Override
	public void run() {
		//如果没有注册,则去register-server注册
		if (!isRegister) {
			// 应该是获取当前机器的信息
			// 包括当前机器的ip地址、hostname，以及配置这个服务监听的端口号
			// 从配置文件里可以拿到,现在图省事,简化了
			RegisterRequest registerRequest = new RegisterRequest();
			registerRequest.setServiceName(SERVICE_NAME);
			registerRequest.setHostname(HOSTNAME);
			registerRequest.setIp(IP);
			registerRequest.setPort(PORT);
			registerRequest.setServiceInstanceId(serviceInstanceId);
			
			RegisterResponse registerResponse = httpSender.register(registerRequest);
			
			System.out.println("服务注册的结果是：" + registerResponse.getStatus() + "......");   
			
			//如果注册
			if (RegisterResponse.SUCCESS.equals(registerResponse.getStatus())) {
				this.isRegister = true;
			}else {
				//如果注册失败,直接返回
				return;
			}
		}
		
		//如果注册成功了,则进入循环发送心跳检查
		if (isRegister) {
			HeartbeatRequest heartbeatRequest = new HeartbeatRequest();
			heartbeatRequest.setServiceInstanceId(serviceInstanceId);
			
			HeartbeatResponse heartbeatResponse = null;
			
			while (true) {
				try {
					heartbeatResponse = httpSender.heartbeat(heartbeatRequest);
					System.out.println("心跳的结果为：" + heartbeatResponse.getStatus() + "......");
					//每隔30秒发送一次心跳检查
					Thread.sleep(30* 1000);
				} catch (Exception e) {
					e.printStackTrace();
				}	
			}
		}
		
	}

}
